package com.mxpio.erp.inventory.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.inventory.vo.WarehouseOrderExportVO;
import com.mxpio.erp.common.order.service.OrderLineService;
import com.mxpio.erp.inventory.policy.impl.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.inventory.entity.WarehouseOrder;
import com.mxpio.erp.common.inventory.entity.WarehouseOrderLine;
import com.mxpio.erp.common.inventory.service.WarehouseOrderLineService;
import com.mxpio.erp.common.inventory.service.WarehouseOrderService;
import com.mxpio.erp.common.jpa.model.Order;
import com.mxpio.erp.common.order.policy.OrderContext;
import com.mxpio.erp.common.order.service.OrderService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpioframework.common.util.BeanReflectionUtils;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "TransferOrderController", description = "仓单接口")
@RestController
@RequestMapping("/erp/inventory/wo/")
public class WarehouseOrderController {
	
	@Autowired
	private WarehouseOrderService warehouseOrderSerivce;
	
	@Autowired
	private WarehouseOrderLineService warehouseOrderLineService;
	
	@Autowired
	private OrderService bizOrderService;
    @Autowired
    private OrderLineService orderLineService;
	@GetMapping("list")
    @Operation(summary = "仓单列表", description = "获取仓单列表（无分页）", method = "GET")
    public Result<List<WarehouseOrder>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<WarehouseOrder> warehouseOrders = warehouseOrderSerivce.list(WarehouseOrder.class, criteria);
        return Result.OK(warehouseOrders);
    }

    @GetMapping("page")
    @Operation(summary = "仓单列表", description = "获取仓单列表（分页）", method = "GET")
    public Result<Page<WarehouseOrder>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<WarehouseOrder> warehouseOrders = warehouseOrderSerivce.listPage(WarehouseOrder.class, page, criteria);
        return Result.OK(warehouseOrders);
    }

    @GetMapping("list/{bizNo}")
    @Operation(summary = "根据bizNo获取仓单", description = "根据bizNo获取仓单", method = "GET")
    public Result<WarehouseOrder> getById(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        WarehouseOrder warehouseOrder = warehouseOrderSerivce.getById(WarehouseOrder.class, bizNo);
        return Result.OK(warehouseOrder);
    }

    @RequestMapping("save")
    @Operation(summary = "保存仓单", description = "保存仓单")
    public Result<WarehouseOrder> save(@RequestBody WarehouseOrder warehouseOrder) {
        warehouseOrderSerivce.save(warehouseOrder,new SmartCrudPolicyAdapter(){
        	@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof WarehouseOrderLine){
        			WarehouseOrder warehouseOrder = context.getParent();
                    ((WarehouseOrderLine) o).setBizNo(warehouseOrder.getBizNo());
        		}
        		return true;
        	}
        });
        return Result.OK(warehouseOrder);
    }
    
    @RequestMapping("excute/{bizNo}")
    @Operation(summary = "执行仓单", description = "执行仓单")
    public Result<Object> excute(@PathVariable(name = "bizNo", required = true) String bizNo, 
    		@RequestBody OrderExcuteVo orderExcuteVo) {
        WarehouseOrder warehouseOrder = warehouseOrderSerivce.getById(WarehouseOrder.class, bizNo);
        OrderContext context = null;
        if (StringUtils.equals(warehouseOrder.getWoType(), NoticeStatusEnums.NoticeType.SO_OUT.getCode())){//销售出库
            context = bizOrderService.execute(warehouseOrder, new SaleWoPolicy(orderExcuteVo.getLines(),orderLineService));
        }else if (StringUtils.equals(warehouseOrder.getWoType(),NoticeStatusEnums.NoticeType.PO_IN.getCode())){
            context = bizOrderService.execute(warehouseOrder, new PurchaseWoPolicy(orderExcuteVo.getLines(),orderLineService));
        }else if (StringUtils.equals(warehouseOrder.getWoType(),NoticeStatusEnums.NoticeType.DO_IN.getCode())){//组织需求接料
            context = bizOrderService.execute(warehouseOrder, new OrganizationDemandWoPolicy(orderExcuteVo.getLines(),orderLineService));
        }else if (StringUtils.equals(warehouseOrder.getWoType(),NoticeStatusEnums.NoticeType.SOA_OUT.getCode())){//报废出库
            context = bizOrderService.execute(warehouseOrder, new DefaultWoWithHoldLotPolicy(orderExcuteVo.getLines(),orderLineService));
        }else if (StringUtils.equals(warehouseOrder.getWoType(),NoticeStatusEnums.NoticeType.IIA_IN.getCode())){//库存质检申请-转移入
            context = bizOrderService.execute(warehouseOrder, new IIAInWoPolicy(orderExcuteVo.getLines(),orderLineService));
        }else if (StringUtils.equals(warehouseOrder.getWoType(),NoticeStatusEnums.NoticeType.FP_IN.getCode())){//送货计划入
            context = bizOrderService.execute(warehouseOrder, new FeedPlanWoInPolicy(orderExcuteVo.getLines(),orderLineService));
        }else{
            context = bizOrderService.execute(warehouseOrder, new DefaultWoPolicy(orderExcuteVo.getLines()));
        }
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }

    @RequestMapping("excutebatch")
    @Operation(summary = "批量执行仓单(按明细)", description = "批量执行仓单(按明细)")
    public Result<Object> excutebat(@RequestBody OrderExcuteVo orderExcuteVo) {
        Result<Object> result = Result.OK();
        try {
            warehouseOrderSerivce.executeBatch(orderExcuteVo);
        } catch (Exception e) {
            result = Result.error(e.getMessage());
        }
        return result;
    }

    @DeleteMapping("remove/{bizNos}")
    @Operation(summary = "根据bizNo删除仓单", description = "删除仓单", method = "DELETE")
    @Transactional(readOnly = false)
    public Result<WarehouseOrder> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "bizNos", required = true) String bizNos) {
        String[] bizNo = bizNos.split(",");
        for(String key : bizNo){
        	Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
        	warehouseOrderLineService.removeBatch(WarehouseOrderLine.class, c);
            warehouseOrderSerivce.delete(WarehouseOrder.class, key);
        }
        return Result.OK();
    }
    
	@PutMapping("open/{bizNo}")
    @Operation(summary = "打开仓单", description = "打开仓单", method = "PUT")
    public Result<? extends Order> open(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
		Order wo = warehouseOrderSerivce.getById(WarehouseOrder.class,bizNo);
    	return bizOrderService.updateCloseStatus(wo, OrderStatusEnums.CloseStatus.OPEN);
    }

    @PutMapping("close/{bizNo}")
    @Operation(summary = "关闭仓单", description = "关闭仓单", method = "PUT")
    public Result<? extends Order> close(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	Order wo = warehouseOrderSerivce.getById(WarehouseOrder.class,bizNo);
    	return bizOrderService.updateCloseStatus(wo, OrderStatusEnums.CloseStatus.CLOSED);
    }
    
    @PutMapping("submit/{bizNo}")
    @Operation(summary = "提交仓单", description = "提交仓单", method = "PUT")
    public Result<? extends Order> submit(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	WarehouseOrder wo = warehouseOrderSerivce.getById(WarehouseOrder.class,bizNo);
    	if(wo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(wo, OrderStatusEnums.BpmnStatus.AUDITING);
    	}else {
    		return Result.error("非开立状态不可提交");
		}
    }

    @PutMapping("audit/{bizNo}")
    @Operation(summary = "审核仓单", description = "审核仓单", method = "PUT")
    public Result<? extends Order> audit(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	WarehouseOrder wo = warehouseOrderSerivce.getById(WarehouseOrder.class,bizNo);
    	if(wo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(wo, OrderStatusEnums.BpmnStatus.AUDITED);
    	}else {
    		return Result.error("非审核中状态不可审核");
		}
    }

    @PutMapping("abandon/{bizNo}")
    @Operation(summary = "弃审仓单", description = "弃审仓单", method = "PUT")
    public Result<? extends Order> abandon(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	WarehouseOrder wo = warehouseOrderSerivce.getById(WarehouseOrder.class,bizNo);
    	if(wo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())||wo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(wo, OrderStatusEnums.BpmnStatus.CREATE);
    	}else{
    		return Result.error("非审核中、已审核状态不可审核");
    	}
    }

    @GetMapping("export")
    @Operation(summary = "仓单列表导出", description = "获取仓单列表导出", method = "GET")
    public Result<List<WarehouseOrderExportVO>> export(@Parameter(description="查询参数") Criteria criteria)  {
        List<WarehouseOrder> warehouseOrders = warehouseOrderSerivce.list(WarehouseOrder.class, criteria);
        List< WarehouseOrderExportVO> exportVOList = new ArrayList<>();
        if (warehouseOrders.size()>0){
            for (WarehouseOrder order:warehouseOrders){
                Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, order.getBizNo());
                List<WarehouseOrderLine> warehouseOrderLines = warehouseOrderLineService.list(WarehouseOrderLine.class, c);
                if (warehouseOrderLines.size()>0){
                    for (WarehouseOrderLine line:warehouseOrderLines){
                        WarehouseOrderExportVO exportVO = new WarehouseOrderExportVO();
                        BeanReflectionUtils.copyProperties(exportVO,order);
                        BeanReflectionUtils.copyProperties(exportVO,line);
                        exportVOList.add(exportVO);
                    }
                }
            }
        }
        return Result.OK(exportVOList);
    }


    @GetMapping("listbynos/{bizNos}")
    @Operation(summary = "根据bizNos获取对应多个仓单及明细", description = "根据bizNos获取对应多个仓单及明细，多个bizNo之间用英文逗号分隔", method = "GET")
    public Result<List<WarehouseOrder>> listByNos(@PathVariable(name = "bizNos", required = true) String bizNos) {
        return warehouseOrderSerivce.listByNos(bizNos);
    }

    @GetMapping("listbynoswithorder/{bizNos}")
    @Operation(summary = "根据bizNos获取对应多个仓单及明细（关联上游业务单）", description = "根据bizNos获取对应多个仓单及明细，多个bizNo之间用英文逗号分隔（关联上游业务单）", method = "GET")
    public Result<List<WarehouseOrder>> listByNosWithOrder(@PathVariable(name = "bizNos", required = true) String bizNos) {
        return warehouseOrderSerivce.listByNosWithOrder(bizNos);
    }

    @GetMapping("is_jit_out/{bizNos}")
    @Operation(summary = "根据bizNo判断仓单是否是JTI对应的出库仓单", description = "根据bizNo判断仓单是否是JTI对应的出库仓单", method = "GET")
    public Result<Boolean> judgeJitOutWo(@PathVariable(name = "bizNos", required = true) String bizNos) {
        return warehouseOrderSerivce.judgeJitOutWo(bizNos);
    }
}
